<!DOCTYPE html>
<html lang="en" xmlns:range="http://www.w3.org/1999/xhtml">
<head xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>学生管理系统</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/bootstraptable/bootstrap-table.min.css">
    <link rel="stylesheet" href="/plugins/fontawesome-free/css/fontawesome.min.css">
    <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="/css/adminlte.min.css">
    <script src="/js/jquery-3.7.1.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script src="/plugins/bootstraptable/bootstrap-table.min.js"></script>
    <script src="/plugins/bootstraptable/locale/bootstrap-table-zh-CN.min.js"></script>
    <script src="/plugins/jqvalidate/jquery.validate.min.js"></script>
    <script src="/plugins/jqvalidate/localization/messages_zh.min.js"></script>
    <script src="/plugins/layui/layui.js"></script>
    <script src="/js/adminlte.min.js"></script>
    <style>
        label.error {
            color: red;
        }

        label.valid {
            color: green;
        }
    </style>
</head>
<body>
<h1 style="text-align: center;color: #0c84ff;">学生管理系统</h1>
<div class="container-fluid">
    <div class="search-box" style="display: flex;">
        <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" style="width: 115px; height: 45px;margin-top:5px;" onclick="modalShow()">
            新增学生
        </button>
        <select class="form-control" id="searchType" name="searchType" style="width: 80px; height: 45px; margin-top:5px;margin-bottom:5px;margin-left:700px">
            <option value="name">姓名</option>
            <option value="id">编号</option>
        </select>
        <input type="text" class="form-control" style="width: 300px; height: 45px; margin-top:5px;margin-bottom:5px;margin-left: 10px;"  placeholder="请输入学生姓名或学号" id="searchBox">
        <button type="button" class="btn btn-primary" style="width: 75px; height: 45px; margin-top:5px;margin-bottom:5px;margin-left: 5px;" onclick="searchStudent();">查询</button>
    </div>
    <table class="table table-bordered" style="text-align: center;"  id="students">
        <thead>
        <tr>
            <th style="width: 100px;text-align: center;">编号</th>
            <th style="width: 200px;text-align: center;">学号</th>
            <th style="width: 100px;text-align: center;">姓名</th>
            <th style="width: 100px;text-align: center;">年龄</th>
            <th style="width: 70px;text-align: center;">操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="myModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">学生信息</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="modalClose()"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">

                <form id="formStudent">
                    <input hidden="hidden" id="id" name="id"/>
                    <div class="form-group">
                        <label for="no">学号</label>
                        <input type="text" class="form-control" id="no" name="no" placeholder="请输入学号" required minlength="10" maxlength="10">
                        <label id="no-error" class="error" for="no"></label>
                    </div>
                    <div class="form-group">
                        <label for="name">姓名</label>
                        <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名" required minlength="2" maxlength="20">
                        <label id="name-error" class="error" for="name"></label>
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
                    </div>
                    <div class="form-group">
                        <label for="sex">性别</label>
                        <!--   下拉列表     -->
                        <select class="form-control" id="sex" name="sex">
                            <option value="1">男</option>
                            <option value="2">女</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄" required min="16" max="30">
                        <label id="age-error" class="error" for="age"></label>
                    </div>
                    <div class="form-group">
                        <label for="score">成绩</label>
                        <input type="text" class="form-control" id="score" name="score" placeholder="请输入成绩" required data-rule-range="[0,100]">
                        <label id="score-error" class="error" for="score"></label>
                    </div>
                </form>
                <!--       表单结束         -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="addStudent();">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
    $("#formStudent").validate({
        submitHandler: function(form) {
            form.submit(); // 表单提交成功
        },
        rules: {
            no: {
                required: true,
                minlength: 10,
                maxlength: 10
            },
            name: {
                required: true,
                minlength: 2,
                maxlength: 20
            },
            age: {
                required: true,
                min: 16,
                max: 30
            },
            score: {
                required: true,
                range: [0, 100]
            }
        },
        messages: {
            no: {
                required: "学号不能为空",
                minlength: "学号长度不能少于10位",
                maxlength: "学号长度不能超过10位"
            },
            name: {
                required: "姓名不能为空",
                minlength: "姓名长度不能少于2位",
                maxlength: "姓名长度不能超过20位"
            },
            age: {
                required: "年龄不能为空",
                min: "年龄不能小于16岁",
                max: "年龄不能大于30岁"
            },
            score: {
                required: "成绩不能为空",
                range: "成绩必须在0-100之间"
            }
        },
        errorPlacement: function(error, element) {
            // 显示错误信息
            $("#" + element.attr("id") + "-error").html(error.text());
        },
        success: function(label) {
            // 隐藏正确提示信息
            $("#" + label.attr("for") + "-error").empty();
        },
        invalidHandler: function(form, validator) {
            // 弹出模态框提示错误信息
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = "";
                $.each(validator.errorList, function(key, value) {
                    message += value.message + "<br/>";
                });
                $("#modal-message").html(message);
                $("#myModal").modal("show");
            }
        }
    });
    function modalShow() {
        $('#myModal').modal('show');
    }
    function modalClose() {
        $('#myModal').modal('hide');
    }
    function addStudent() {
        var data = $("#formStudent").serialize();
        var id = $("#id").val();
        if (id) {
            // 如果id存在，则执行更新操作
            $.ajax({
                url: "/api/student/update",
                method: "put",
                data: data + "&id=" + id,  // 将id作为数据参数发送到后端
            }).done(function () {
                // loadTable();
                $('#myModal').modal('hide');
            });
        } else {
            // 如果id不存在，则执行新建操作
            $.ajax({
                url: "/api/student/insert",
                method: "post",
                data: data
            }).done(function () {
                // loadTable();
                $('#myModal').modal('hide');
            });
        }
    }
    function searchStudent() {
        var searchTerm = $("#searchBox").val();  // 获取搜索框中的输入值
        var searchType = $("#searchType").val();  // 获取搜索类型的值
        $.ajax({
            url: "/api/student/search",
            method: "get",
            data: {term: searchTerm, type: searchType},  // 将搜索词作为参数发送到后端
        }).done(function (data) {
            updateTable(data);  // 调用更新表单函数，更新表单显示为查询到的数据
        });
    }
    function updateTable(data) {
        var len = data.length;
        var html = "";
        for (var i = 0; i < len; i++) {
            var item = data[i];
            html += "<tr>"
                + "<td>" + item.id + "</td>"
                + "<td>" + item.no + "</td>"
                + "<td>" + item.name + "</td>"
                + "<td>" + item.sex + "</td>"
                + "<td>" + item.age + "</td>"
                + "<td>" + item.score + "</td>"
                + "<td><a href='#' onclick='editStudent(" + item.id + ");'>编辑</a> | <a href='#' onclick='deleteStudent(" + item.id + ");'>删除</a></td>"
                + "<tr>";
        }
        $("#students").html(html);  // 更新表格数据
    }
    function editStudent(id) {
        $('#myModal').modal('show');
        $.ajax({
            url: "/api/student/get/" + id
        }).done(function (data) {
            $("#id").val(data.id);
            $("#no").val(data.no);
            $("#name").val(data.name);
            $("#password").val("");
            $("#sex").val(data.sex);
            $("#age").val(data.age);
            $("#score").val(data.score);
        });
    }
    // function editStudent(id) {
    //     layer.open({
    //         type: 2,
    //         content: "/api/student/update/" + id,
    //         area: ['600px', '400px']
    //     });
    // }
    layui.use(['layer','form'], function() {
        var layer = layui.layer
            ,form=layui.form;
    });
    function deleteStudent(id) {
        if (confirm("确定要删除该学生吗？")) {
            $.ajax({
                url: "/api/student/delete/"+id,
                method: "delete"
            }).done(function () {
                // loadTable();
                $('#myModal').modal('hide');
            });
        }
    }
    // function loadTable() {
    //     $.ajax({
    //         url: '/api/student/list'
    //     }).done(function (data) {
    //         var len = data.length;
    //         var html = "";
    //         for (var i = 0; i < len; i++) {
    //             var item = data[i];
    //             html += "<tr>"
    //                 + "<td>" + item.id + "</td>"
    //                 + "<td>" + item.no + "</td>"
    //                 + "<td>" + item.name + "</td>"
    //                 + "<td>" + item.sex + "</td>"
    //                 + "<td>" + item.age + "</td>"
    //                 + "<td>" + item.score + "</td>"
    //                 + "<td><a href='#' onclick='editStudent(" + item.id + ");'>编辑</a> | <a href='#' onclick='deleteStudent(" + item.id + ");'>删除</a></td>"  // 添加删除按钮
    //                 + "<tr>";
    //         }
    //         $("#students").html(html);
    //         console.log(data);
    //     });
    // }
    $(function () {
        // loadTable();
        // $('#formStudent').validate({
        //     submitHandler: addStudent //验证通过执行
        // });
        $('#students').bootstrapTable({
            method: 'get', // 服务器数据的请求方式 get or post
            url:"/api/student/list", // 服务器数据的加载地址
            striped: true, //是否显示行间隔色
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true, //是否显示分页（*）
            sortable: false, //是否启用排序
            sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 3, //每页的记录行数（*）
            pageList: [3, 5 ], //可供选择的每页的行数（*）
            strictSearch: false,
            minimumCountColumns: 2, //最少允许的列数
            clickToSelect: true, //是否启用点击选中行
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            cardView: false,
            detailView: false, //是否显示详细视图
            smartDisplay: false,
            queryParams: function(params) {
                return {
                    pageSize: params.limit,
                    pageNum: params.offset / params.limit + 1
                };
            },
            columns: [{
                checkbox: true
            },{
                field: 'id',
                title: '编号'
            },{
                field: 'no',
                title: '学号'
            },{
                field: 'name',
                title: '姓名'
            },{
                field: 'age',
                title: '年龄'
            }, {
                field: 'score',
                title: '成绩'
            },{
                title: '操作',
                formatter: function (value, row) {
                    var editLink = '<a href="#" onclick="editStudent(' + row.id + ');"><i class="fas fa-edit"></i> </a>';
                    var deleteLink = '<a href="#" onclick="deleteStudent(' + row.id + ');"><i class="fas fa-trash"></i></a>';
                    return editLink + '  |  ' + deleteLink;
                }
            }]
        });
    });
</script>
</body>
</html>